<template>
    <v-header></v-header>
    <div class="page">
        <md-editor v-model="rawContent" :onHtmlChanged="onHtmlChanged" :onUploadImg="onUpload"/>
        <div class="bottom-btn">
            <el-button type="primary" @click="toPublish">发布</el-button>
            <el-button @click="save">保存</el-button>
        </div>
    </div>
    <el-drawer
            title="请填写文章基本信息"
            v-model="drawer"
            direction="btt"
            size="80%"
            :before-close="handleClose">
        <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="rules"
                label-width="80px"
                class="demo-ruleForm"
                :size="formSize">
            <el-form-item label="文章标题" prop="title">
                <el-input v-model="ruleForm.title" placeholder="请输入文章标题"/>
            </el-form-item>
            <el-form-item label="文章标题" prop="title">
                <el-input type="textarea" minlength="50" maxlength="200" v-model="ruleForm.abstraction" placeholder="请输入文章摘要" show-word-limit/>
            </el-form-item>
            <el-form-item label="文章类别" prop="type">
                <el-select v-model="ruleForm.type" placeholder="请选择文章类别">
                    <el-option v-for="item in types" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="发布状态" prop="state">
                <el-select v-model="ruleForm.state" placeholder="请选择文章类别">
                    <el-option label="草稿" :value="0"/>
                    <el-option label="发布" :value="1"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="publish">提交</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>

<script>
    import MdEditor from 'md-editor-v3';
    import 'md-editor-v3/lib/style.css';
    import {ref, reactive, onMounted} from 'vue';
    import {modifyArticle, getArticle, getTypeList} from "../api/";
    import { useRouter,useRoute } from "vue-router";
    import vHeader from "./components/Header.vue";
    import {ElMessage, ElLoading} from "element-plus";
    import axios from 'axios';
    export default {
        name: "EditorUpdate",
        components: {
            MdEditor,
            vHeader
        },
        setup() {
            const router = useRouter();
            const route = useRoute();
            const rawContent = ref('');
            const htmlContent = ref('');
            const title = ref('');
            const drawer = ref(false);
            const rules = reactive({
                title: [
                    {required: true, message: '请输入文章标题', trigger: 'blur'},
                    {min: 10, max: 64, message: '标题长度必须大于10小于64', trigger: 'blur'},
                ],
                abstraction: [
                    {required: true, message: '请输入文章摘要', trigger: 'blur'},
                    {min: 50, message: '摘要长度必须大于50', trigger: 'blur'},
                ],
                type: [
                    {
                        required: true,
                        message: '请选择文章类别',
                        trigger: 'blur',
                    }
                ],
                state: [
                    {
                        required: true,
                        message: '请选择发布状态',
                        trigger: 'blur',
                    }
                ]
            });
            const ruleForm = ref({
                title: '',
                type: null,
                abstraction: '',
                state: null,
            });
            const types = ref([]);
            const id = route.params.id;

            onMounted(() => {
                getTypeList().then(res => {
                    if (res.code === 200) {
                        types.value = res.data;
                    }
                })
            });

            const initData = async () => {
                const loadingInstance = ElLoading.service({});
                const res = await getArticle(id);
                if (res.code === 200) {
                    ruleForm.value.title = res.data.title,
                    ruleForm.value.type = res.data.typeId,
                    ruleForm.value.abstraction = res.data.abstraction,
                    ruleForm.value.state = res.data.state,
                    rawContent.value = res.data.rawContent,
                    htmlContent.value = res.data.htmlContent
                } else {
                    ElMessage.error(res.message);
                }
                loadingInstance.close()
            };
            initData();



            const onHtmlChanged = (e) => {
                htmlContent.value = e;
            };


            const onUpload = async (files, callback) => {
                const loadingInstance = ElLoading.service({
                    text: "uploading..."
                });
                console.log("上传", files);
                const res = await Promise.all(
                    files.map((file) => {
                        return new Promise((rev, rej) => {
                            const form = new FormData();
                            form.append('file', file);
                            axios.post('/api/file/upload', form, {
                                    headers: {
                                        'Content-Type': 'multipart/form-data',
                                        'token': localStorage.getItem("token")
                                    }
                                })
                                .then((res) => rev(res))
                                .catch((error) => rej(error));
                        });
                    })
                );
                console.log(res);
                callback(res.map((item) => item.data.data));
                loadingInstance.close();
            };

            const save = () => {

            };
            const toPublish = async () => {
                drawer.value = true;
            };
            const publish = () => {
                let form = {
                    id: id,
                    title: ruleForm.value.title,
                    typeId: ruleForm.value.type,
                    rawContent: rawContent.value,
                    htmlContent: htmlContent.value,
                    state: ruleForm.value.state,
                    abstraction: ruleForm.value.abstraction
                };
                modifyArticle(form).then(res => {
                   if (res.code === 200) {
                       ElMessage.success("修改成功");
                       router.push("/");
                   } else {
                       ElMessage.error(res.message);
                   }
                }).catch(e => {
                    console.error(e);
                    ElMessage.error("网络繁忙！");
                });
            };
            const handleClose = () => {
                drawer.value = false;
            };
            return {
                rawContent,
                htmlContent,
                title,
                drawer,
                types,
                rules,
                ruleForm,
                handleClose,
                onHtmlChanged,
                toPublish,
                publish,
                save,
                onUpload
            }
        }
    }
</script>

<style scoped>
    #md-editor-v3 {
        height: 80vh;
        border-radius: 10px;
    }
    .page {
        margin-top: 70px;
        margin-right: 10px;
        margin-left: 10px;
    }
    .header {
        z-index: 100;
    }
    .bottom-btn {
        margin-top: 10px;
    }
</style>